package org.study.dsm.mybatisplus.config;

import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年04月27日
 */
@Configuration
@MapperScan(basePackages = {"org.study.dsm.mybatisplus.mapper"})
public class DataSourceConfig {
    @Bean("druidMasterDataSource")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource druidMasterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("druidSaveDataSource")
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource druidSaveDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("hikariSlaveDataSource")
    @ConfigurationProperties("spring.datasource.hikari.slave")
    public DataSource hikariSlaveDataSource() {
        return new HikariDataSource();
    }

    @Primary
    @Bean
    public DynamicDataSource dynamicDataSource(DataSource druidMasterDataSource,
                                               DataSource druidSaveDataSource,
                                               DataSource hikariSlaveDataSource) {
        // 设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(druidMasterDataSource);
        Map<Object, Object> dataSourceMap = new HashMap<>() {{
            this.put(CommonConstant.MASTER, druidMasterDataSource);
            this.put(CommonConstant.SLAVE + "_druid", druidSaveDataSource);
            this.put(CommonConstant.SLAVE + "_hikari", hikariSlaveDataSource);
        }};
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        // 将数据源信息备份在defineTargetDataSources中
        // dynamicDataSource.setDefineTargetDataSources(dataSourceMap);
        return dynamicDataSource;
    }
}
